import { inject } from 'vue'
import { message } from 'ant-design-vue'
import { isDef } from '@/core/utils/Common'
import { cloneDeep } from 'lodash-es'
// import { useStore} from 'vuex'
// const store = useStore()

/**
 * 通用的表单重置、保存功能
 * 示测试
 * options: {state: null, remoteApi: '', formState: null, original: null, formRef:null }
 */
export default function (options) {
  const refreshPage = inject('refreshPage', () => console.error('没有提供refreshPage接口事件,请查看代码'))
  const refreshData = inject('refreshData', () => console.error('没有提供refreshData接口事件,请查看代码'))
  // // 将state重置为初始值 
  // const resetState =(state, originalData)=>{
  //   Object.keys(state).forEach(key=>{
  //     const value = originalData[key]
  //     if (typeof value=== 'object' && value !==null){
  //       state[key] = resetState(reactive(value), value)
  //     }else{
  //       state[key] =markRaw(value) // markRaw 将对象标记为非响应式。
  //     }
  //   })
  //   return state
  // }
  
  // 重置
  const onCancel = () => {
    options.state.visible = false
    //formRef.value.resetFields()
    options.formRef.value.clearValidate()
  }
  // 完成 保存数据
  const onFinish = (values) => {
    // console.info(JSON.stringify(values))
    options.state.loading = true
    options.remoteApi.saveData(values).then(res => {
      refreshData()
      message.success(res.msg)
      options.state.visible = false
    })
    //.catch(err => { message.error(JSON.stringify(err))})
      .finally(() => {
        options.state.loading = false
        options.formRef.value.clearValidate()
      })
    
  }
  // 初始化数据Initalizer 初始化
  const InitializeData = async (primaryKey) => {
    options.state.visible = true
    Object.keys(options.formState).forEach(key=>{
      delete options.formState[key]
    })
    Object.assign(options.formState , cloneDeep(options.original) )
    //resetState(options.formState, options.original)
    //
    if (isDef(primaryKey)) {
      options.state.loading = true
      try{
        let res = await options.remoteApi.getFormModelById(primaryKey)
        // console.info('是对PUT方法的补充................')
        if (res.code == 0) {
          Object.assign(options.formState, res.data)
        }
      }catch(err){
        console.error(err)
        options.state.visible = false
      }finally{
        options.state.loading = false
      }
    }
  }

  return {InitializeData, onCancel, onFinish, refreshData, refreshPage}
}